import React, { useState } from "react";
import useStyles from "./useStyles";
import Select from "../Select";
import { Delete as DeleteIcon } from "@ct0/icons";
import ConditionItemValue from "./ConditionItemValue";
import { getOperatorsByField } from "./utils";
import { Kuozhan as KuozhanIcon } from "@ct0/icons";
import Joint from "./components/Joint";
import {
  NestFilterCondition,
  NestFilterConditionItemValue,
  NestFilterFields,
  NestFilterFieldValue,
  NestFilterJoint,
  NestFilterOperator,
} from "./type";

export default ConditionItem;

function getOperatorOptions(key: string, fields: NestFilterFields) {
  let field = fields[0];
  fields.map((i) => {
    if (i.key == key) field = i;
  });

  return getOperatorsByField(field).map((i) => ({
    label: i.label,
    value: i.value,
    key: i.value,
  }));
}

interface NestFilterConditionItemProps {
  seq: number;
  condition: NestFilterCondition;
  joint: NestFilterJoint;
  fields: NestFilterFields;
  isFirst: boolean;
  showError?: boolean;
  disabled?: boolean;
  onChange: (
    seq: number,
    joint: NestFilterJoint,
    condition: NestFilterCondition
  ) => void;
  onDelete: (seq: number) => void;
  onExpand: (seq: number) => void;
}

function ConditionItem({
  condition,
  fields,
  joint,
  seq,
  isFirst,
  showError,
  disabled,
  onChange,
  onDelete,
  onExpand,
}: NestFilterConditionItemProps) {
  const classes = useStyles();
  const { key, operator, value } = condition;
  const [fieldOptions, setFieldOptions] = useState(() =>
    fields.map((i) => ({
      key: i.key,
      value: i.key,
      label: i.label,
    }))
  );

  const fieldTextChangeHandler = (text: string) => {
    const options: Array<{ key: string; value: string; label: string }> = [];
    fields.map((f) => {
      if (f.key.includes(text) || f.label.includes(text))
        options.push({ key: f.key, value: f.key, label: f.label });
    });
    setFieldOptions(options);
  };

  const update = (params: NestFilterConditionItemValue) => {
    onChange(seq, params.joint || joint, {
      key: params.key || key,
      value: typeof params.value == "undefined" ? value : params.value,
      operator: params.operator || operator,
    });
  };

  const changeHandler = (value: Array<NestFilterFieldValue>) => {
    update({ value });
  };

  let field = fields[0];
  fields.map((i) => {
    if (i.key == key) field = i;
  });

  const operators = getOperatorOptions(key, fields);

  return (
    <div className={classes.clauseItem}>
      <div className={classes.joint}>
        {!isFirst && (
          <Joint
            value={joint}
            onChange={(v) => update({ joint: v })}
            disabled={disabled}
          />
        )}
      </div>
      <Select
        search
        className={classes.clauseKey}
        disabled={disabled}
        value={key}
        onInputChange={fieldTextChangeHandler}
        options={fieldOptions}
        onChange={(v) => {
          const key = String(v);
          update({
            key,
            operator: getOperatorOptions(key, fields)[0].value,
            value: [],
          });
        }}
      />
      <div className={classes.clauseSpace}></div>
      <Select
        className={classes.clauseOperator}
        value={operator}
        disabled={disabled}
        options={operators}
        onChange={(v) =>
          update({ operator: v as NestFilterOperator, value: [] })
        }
      />
      <div className={classes.clauseSpace}></div>
      <div className={classes.clauseValue}>
        <ConditionItemValue
          operator={operator}
          field={field}
          value={value}
          showError={showError}
          disabled={disabled}
          onChange={changeHandler}
        />
      </div>
      <div className={classes.clauseSpace}></div>
      {!disabled && (
        <div className={classes.clauseIcon} onClick={() => onExpand(seq)}>
          <KuozhanIcon />
        </div>
      )}
      {!disabled && (
        <span className={classes.clauseIcon} onClick={() => onDelete(seq)}>
          <DeleteIcon />
        </span>
      )}
    </div>
  );
}
